package icu.makka.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import icu.makka.yygh.common.exception.CustomException;
import icu.makka.yygh.enums.AuthStatusEnum;
import icu.makka.yygh.model.user.Patient;
import icu.makka.yygh.model.user.UserInfo;
import icu.makka.yygh.result.ResultCodeEnum;
import icu.makka.yygh.result.helper.JwtHelper;
import icu.makka.yygh.user.mapper.UserInfoMapper;
import icu.makka.yygh.user.service.PatientService;
import icu.makka.yygh.user.service.UserInfoService;
import icu.makka.yygh.vo.user.LoginVo;
import icu.makka.yygh.vo.user.UserAuthVo;
import icu.makka.yygh.vo.user.UserInfoQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private PatientService patientService;

    /**
     * 认证审批 2:通过 -1:不通过
     * @param userId
     * @param authStatus
     * @return
     */
    @Override
    public Boolean approval(Long userId, Integer authStatus) {
        log.info("业务层，认证审批");

        if (authStatus.intValue() == 2 || authStatus.intValue() == -1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 按id查询用户详情
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> show(Long userId) {
        log.info("业务层，按id查询用户详情");

        Map<String, Object> map = new HashMap<>();
        //根据userId查询用户信息
        UserInfo userInfo = this.packUserInfo(baseMapper.selectById(userId));
        //根据userId查询就诊人信息
        List<Patient> patientList = patientService.findAllByUserId(userId);
        //封装参数
        map.put("userInfo", userInfo);
        map.put("patientList", patientList);

        return map;
    }

    /**
     * 用户锁定
     * @param userId
     * @param status
     * @return
     */
    @Override
    public boolean lock(Long userId, Integer status) {
        log.info("业务层，用户锁定");

        if (status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            this.updateById(userInfo);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 用户列表
     * @param pageParam
     * @param userInfoQueryVo
     * @return
     */
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        log.info("业务层，用户列表");

        //UserInfoQueryVo获取条件值
        String name = userInfoQueryVo.getKeyword();                     //用户名称
        Integer status = userInfoQueryVo.getStatus();                   //用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();           //用户认证
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();  //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();      //结束时间
        //封装查询条件
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(name), UserInfo::getName, name);
        queryWrapper.eq(status != null, UserInfo::getStatus, status);
        queryWrapper.eq(authStatus != null, UserInfo::getAuthStatus, authStatus);
        queryWrapper.ge(!StringUtils.isEmpty(createTimeBegin), UserInfo::getCreateTime, createTimeBegin);
        queryWrapper.le(!StringUtils.isEmpty(createTimeEnd), UserInfo::getCreateTime, createTimeEnd);
        //调用mapper方法
        Page<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, queryWrapper);
        //将编号转化成对应值封装
        userInfoPage.getRecords().stream().forEach(userInfo -> {
            this.packUserInfo(userInfo);
        });

        return userInfoPage;
    }

    /**
     * 将编号转化为对应值封装
     * @param userInfo
     */
    private UserInfo packUserInfo(UserInfo userInfo) {
        log.info("将编号转化为对应值封装，userInfo={}", userInfo);
        //处理认证状态编码
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态0 1
        userInfo.getParam().put("statusString", userInfo.getStatus().intValue() == 0 ? "锁定" : "正常");
        return userInfo;
    }

    /**
     * 用户认证接口
     * @param userId
     * @param userAuthVo
     */
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证人姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        //将状态改为1，未认证->认证中
        userInfo.setAuthStatus(1);
        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    /**
     * 用户登录
     * @param loginVo
     * @return
     */
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        log.info("业务层，用户登录");

        //从loginVo中获取输入的手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //判断手机号和验证码是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            log.info("手机号或验证码为空，phone={}，code={}", phone, code);
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        //判断手机验证码和输入的验证码是否一致
        if (!code.equals(redisTemplate.opsForValue().get(phone))) {
            log.info("手机验证码出错，手机号：{}，输入的验证码：{}", phone, code);
            //若不一致，则抛出参数错误异常
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }

        //判断是否为第一次登录，根据手机号查询数据库，如果不存在相同手机号就是第一次登录
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone, phone);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);

        if (null == userInfo) {
            userInfo = new UserInfo();
            userInfo.setName("");
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            this.save(userInfo);
        }
        //校验是否被禁用
        if(userInfo.getStatus() == 0) {
            throw new CustomException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //是第一次，直接登录
        //返回登录信息
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //jwt 生成 token 字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        //返回结果
        return map;
    }
}
